package collection;

import java.util.ArrayList;

import database.DatabaseSupport;
import mediaitem.*;

public class Collection
{
	private String name;
	private ArrayList<Collection> parents;
	private ArrayList<Collection> children;
	private ArrayList<MediaItem> itemsList;
	
	public Collection(String name, ArrayList<Collection> parents)
	{
		this.name = name;
		this.parents = new ArrayList<Collection>();
		this.setParents(parents);

		this.children = new ArrayList<Collection>();
	}

	public boolean clearParents()
	{
		for (Collection parent : this.parents)
		{
			this.removeFrom(parent);
		}

		return true;
	}

	public static boolean createCollection(String name, ArrayList<Collection> parentCollections)
	{
		return DatabaseSupport.putCollection(new Collection(name, parentCollections));
	}

	public static boolean deleteCollection(String name)
	{
		Collection c = DatabaseSupport.getCollection(name);
		c.clearParents();
		return DatabaseSupport.removeCollection(c);
	}

	public static Collection getCollection(String name)
	{
		return DatabaseSupport.getCollection(name);
	}

	public boolean setChild(Collection coll){
		return children.add(coll);
	}
	
	public boolean removeChild(Collection child)
	{
		return children.remove(child);
	}
	
	public boolean removeFrom(Collection parent)
	{
		return parents.remove(parent);
	}

	public boolean setName(String newName)
	{
		this.name = newName;
		return true;
	}

	public String getName() {
		return name;
	}
	
	public boolean setParents(ArrayList<Collection> newParents)
	{
		for (Collection parent : this.parents)
		{
			if (!newParents.contains(parent))
			{
				this.removeFrom(parent);
			}
		}

		for (Collection parent : parents)
		{
			this.parents.add(parent);
			parent.children.add(this);
		}

		return true;
	}

	public static boolean updateCollectionName(String oldName, String newName)
	{
		Collection c = DatabaseSupport.getCollection(oldName);
		c.setName(newName);
		return true;
	}

	public static boolean updateCollectionParents(String name, ArrayList<Collection> newParents)
	{
		Collection c = DatabaseSupport.getCollection(name);
		c.setParents(newParents);
		return true;
	}
	
	public boolean addMediaItem(MediaItem item){
		return (itemsList.add(item) & item.addCollection(this));
	}
	
	public boolean removeMediaItem(MediaItem item){
		return (itemsList.remove(item) & item.removeCollection(this));
	}

	public boolean addParent(Collection newParent) {
		// TODO Auto-generated method stub
		parents.add(newParent);
		return true;
	}
}
